package demo

import (
	"fmt"
	"path"
	"server/dao"
	"server/models"
	"server/utils"
	"time"

	"github.com/360EntSecGroup-Skylar/excelize/v2"
	"github.com/gin-gonic/gin"
)

func ExcelExport(c *gin.Context) {
	name := c.Query("name")
	phone := c.Query("phone")
	fmt.Println(name)
	payload := fmt.Sprintf(`
		{
			"name":"%v",
			"phone":"%v",
			"user_id":%v
		}
	`, name, phone, 2)
	dao.RdbLPush("excel_export", payload)
	// 正常返回数据
	c.JSON(
		200,
		utils.DealResponse(utils.Response{
			"data": "ok",
		}),
	)
}

func ExcelImport(c *gin.Context) {
	// 获取上传文件
	files, _ := c.FormFile("file")
	// 设置文件需要保存的指定位置并设置保存的文件名字
	dst := path.Join("./upload", files.Filename)
	// 上传文件到指定的路径
	c.SaveUploadedFile(files, dst)
	f, errFile := excelize.OpenFile(dst)
	if errFile != nil {
		c.AbortWithError(500, errFile)
		return
	}

	// 获取 Sheet1 上所有单元格
	rows, errRows := f.GetRows("Sheet1")
	if errRows != nil {
		c.AbortWithError(500, errRows)
		return
	}
	fmt.Printf("rows len:%#v\n", len(rows))
	for index, row := range rows {
		if index > 0 {
			var doc models.AdminUser
			newDoc := &models.AdminUser{
				Name:  row[0],
				Phone: row[1],
			}
			errFirst := dao.DB.First(&doc, "phone = ?", row[1]).Error
			fmt.Printf("res:%#v\n row:%#v\n", doc, row)
			if errFirst != nil {
				newDoc.Status = 1
				newDoc.Password = "e10adc3949ba59abbe56e057f20f883e"
				newDoc.CreatedTime = uint64(time.Now().Unix())
				newDoc.UpdatedTime = uint64(time.Now().Unix())
				errCreate := dao.DB.Model(&models.AdminUser{}).Create(&newDoc).Error
				if errCreate != nil {
					c.AbortWithError(500, errCreate)
					return
				}
			}

		}
	}

	// 正常返回数据
	c.JSON(
		200,
		utils.DealResponse(utils.Response{
			"data": "ok",
		}),
	)
}
